<template>
  <div class="app-container">
    <div class="header">
      <el-form ref="queryFormRef" :inline="true" :model="queryParams">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="queryParams.keywords" placeholder="请输入角色名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="角色状态" style="width: 150px" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery" :loading="loading">查询</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="footer">
      <div class="util">
        <el-button type="primary" v-hasPermi="['sys:role:add']" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>
          新增角色
        </el-button>
      </div>
      <div class="table-inner">
        <el-table v-loading="loading" :data="roleList" style="width: 100%" border>
          <el-table-column prop="sort" label="序号" width="80" align="center" />
          <el-table-column prop="name" label="角色名称" show-overflow-tooltip />
          <el-table-column prop="code" label="角色标识" show-overflow-tooltip />
          <el-table-column prop="status" label="角色状态" width="120" align="center">
            <template #default="scope">
              <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" inline-prompt active-text="启用"
                inactive-text="禁用" @change="handleStatusChange($event, scope.row)" />
            </template>
          </el-table-column>
<!--          <el-table-column prop="remark" label="角色描述" :show-overflow-tooltip="true" width="180" />-->
          <el-table-column prop="createTime" label="创建时间" width="160" show-overflow-tooltip />
          <el-table-column label="操作" width="220" align="center" fixed="right">
            <template #default="scope">
              <el-button type="primary" link icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['sys:role:edit']">编辑</el-button>
              <el-button type="primary" link icon="Edit" @click="handleMenus(scope.row)" v-hasPermi="['sys:role:perm']">权限</el-button>
              <el-button type="danger" link icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['sys:role:delete']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination v-if="total > 0" v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize" :page-sizes="[10, 20, 30, 50]" :total="total"
          layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <RoleDrawer ref="roleDrawerRef" @success="getList" />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessageBox, ElMessage, FormInstance } from 'element-plus'
import { Search, Plus, Refresh } from '@element-plus/icons-vue'
import RoleDrawer from './components/roleDrawer.vue'
import { listRole, delRole, changeRoleStatus } from '@/api/roles'

// 遮罩层
const loading = ref(false)
// 总条数
const total = ref(0)
// 角色列表
const roleList = ref([])
// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keywords: '',
  status: undefined
})
// 查询表单ref
const queryFormRef = ref<FormInstance>()
// 抽屉ref
const roleDrawerRef = ref()

/** 查询角色列表 */
const getList = async () => {
  loading.value = true
  try {
    const res = await listRole(queryParams)
    roleList.value = res.data.list
    total.value = res.data.total
  } catch (error: any) {
    ElMessage.error(error.msg || '查询失败')
  } finally {
    loading.value = false
  }
}

/** 查询按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 新增按钮操作 */
const handleAdd = () => {
  roleDrawerRef.value.show()
}

/** 修改按钮操作 */
const handleUpdate = (row: any) => {
  roleDrawerRef.value.show(row)
}
const handleMenus = (row: any) => {
  roleDrawerRef.value.show(row, true)
}
/** 删除按钮操作 */
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `是否确认删除名称为"${row.name}"的角色?`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        await delRole(row.id)
        getList()
        ElMessage.success('删除成功')
      } catch (error: any) {
        ElMessage.error(error.msg || '删除失败')
      }
    })
    .catch(() => { })
}

/** 角色状态修改 */
const handleStatusChange = async (value: string, row: any) => {
  const text = value === '0' ? '启用' : '禁用'
  try {
    await ElMessageBox.confirm(
      `确认要${text}"${row.name}"角色吗?`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 创建 URLSearchParams 对象
    const params = new URLSearchParams()
    params.append('roleId', row.id)
    params.append('status', value)

    await changeRoleStatus(params, row.id)
    ElMessage.success('修改成功')
  } catch (error: any) {
    // 如果用户取消或者API调用失败，回退状态
    row.status = value === '0' ? '1' : '0'
    if (error !== 'cancel') { // 非取消操作才提示错误
      ElMessage.error(error.msg || '修改失败')
    }
  }
}

/** 分页大小改变 */
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  getList()
}

/** 分页页码改变 */
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val
  getList()
}

/** 初始化 */
onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.header {
  display: flex;
  padding: 16px 16px 0px 16px;
  margin-bottom: 16px;
  border-radius: 4px;
  background: white;
  box-shadow: 0 0 12px rgb(0 0 0 / 5%);
}

.footer {
  flex: 1;
  display: flex;
  padding: 16px;
  flex-direction: column;
  border-radius: 4px;
  overflow: hidden;
  background: white;
  box-shadow: 0 0 12px rgb(0 0 0 / 5%);
  position: relative;
  box-sizing: border-box;

  .util {
    margin-bottom: 15px;
    display: flex;
    justify-content: flex-end;
    flex-shrink: 0;
  }

  .table-inner {
    flex: 1;
    position: relative;
    display: flex;
    flex-direction: column;
    gap: 16px;
  }
}
</style>